package uk.ac.glasgow.oose2.gcf.model.operation.stack.math;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import uk.ac.glasgow.oose2.gcf.model.CalculatorException;
import uk.ac.glasgow.oose2.gcf.model.operation.stack.StackOperation;

public abstract class MathOperation extends StackOperation<Double> {
	private Integer numArgs;
	
	public MathOperation(Stack<Double> stack, Integer numArgs){
		super(stack);
		this.numArgs = numArgs;
	}
	
	@Override
	public void invoke() throws CalculatorException {

		List<Double> args = new ArrayList<Double>();
				
		try {
			int i = 0;
			while (i < numArgs){
				args.add(stack.pop());
				i++;
			}
		} catch (Exception ex) {
			throw new CalculatorException(this.getClass().getName(), "empty stack while popping ["+numArgs+"] args");
		}
		stack.push(doOp(args));
	}

	protected abstract Double doOp(List<Double> args) throws CalculatorException;
}
